<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <link rel="icon" type="image/png" sizes="16x16" href="../../icons/favicon-16x16.png">
  <script type="text/javascript" src="../../js/jquery.2.1.4.min.js"></script>
  <script type="text/javascript" src="../../plugins/page/jquery.page.js"></script>
  <link rel="stylesheet" href="../../plugins/ol/ol.css" type="text/css">
  <link rel="stylesheet" href="../../plugins/loading/loading.css" type="text/css">
  <style type="text/css">
    @import url('../../plugins/page/jQuery.page.css');
    @font-face {
      font-family: Material Icons Outlined;
      font-style: normal;
      font-weight: 400;
      src: url(../../fonts/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUcel5euIg.312bdf7e.woff2) format("woff2"), url(../../fonts/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUcY.42ced8c1.woff) format("woff")
    }

    .material-icons-outlined {
      font-family: Material Icons Outlined;
      font-weight: 400;
      font-style: normal;
      display: inline-block;
      line-height: 1;
      text-transform: none;
      letter-spacing: normal;
      word-wrap: normal;
      white-space: nowrap;
      direction: ltr;
      -webkit-font-smoothing: antialiased;
      text-rendering: optimizeLegibility;
      -moz-osx-font-smoothing: grayscale;
      -webkit-font-feature-settings: "liga";
      font-feature-settings: "liga"
    }
    html, body, .map {
      width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
    }
    .map {
      width: 100%;
      height: 98vh;
    }
    .ol-attribution{
      display: none
    }
    .data-btn{
      position: absolute;
      top: 75px;
      left: 10px;
      z-index: 1000;
      display: block;
      margin: 1px;
      padding: 0;
      color: #fff;
      font-size: 1.14em;
      font-weight: 500;
      text-decoration: none;
      text-align: center;
      height: 1.375em;
      width: 1.375em;
      line-height: .4em;
      background-color: rgba(0,60,136,.5);
      border: none;
      border-radius: 2px;
    }
    .data-div{
      text-align: center;
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100vw;
      height: 25vh;
      z-index: 1000;
      background-color: #fff;
    }
    .table-div{
      width: 100vw;
      overflow-x: auto;
    }
    table{
      width: 100%;
      border-spacing: 0;
      /*表格设置合并边框模型*/
      border-collapse: collapse;
      text-align: center;
      color: #444;
    }
    table>tbody{
      height: 14.2vh;
      display: block;
      overflow-y: auto;
      overflow-x: auto;
      font-size: 14px;
    }
    table thead{
      font-size: 16px;
      background-color: #EFEEEF;
    }
    tbody tr:nth-child(even){
      background-color: #f8f9f9;
    }
    table thead,
    tbody tr {
      display: table;
      width: 99vw;
      table-layout: fixed;
      height: 25px;
    }
    /*关键设置：滚动条默认宽度是16px 将thead的宽度减16px*/
    table thead {
      width: calc( 100vw - 1em)
    }
    tbody tr:hover{
      background-color: #D1E9F9;
      cursor: pointer;
    }
    table td,
    table th{
      width: 100px;
      word-wrap: break-word;
    }
    .hide{
      display: none;
    }
    .tr-active {
      background-color: #D1E9F9 !important;
    }
    .active{
      background-color: rgba(0,60,136,.7);
    }
    .data-title{
      font-weight: bold;
      width: 100%;
      height: 30px;
      line-height: 29px;
      background-color: #526f82;
      color: #fff;
      text-align: left;
    }
    ::-webkit-scrollbar {/*滚动条整体样式*/
      width: 8px;     /*高宽分别对应横竖滚动条的尺寸*/
      height: 8px;
    }
    ::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
      border-radius: 5px;
      -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
      background: #676968;
    }
    ::-webkit-scrollbar-track {/*滚动条里面轨道*/
      -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
      border-radius: 5px;
      background: transparent;
    }
    .no-data{
      position: absolute;
      top: 110px;
      left: 49vw;
    }
  </style>
  <script src="../../plugins/ol/ol.js"></script>
  <script src="../../js/proj4.js"></script>
  <title>PowerGIS</title>
</head>
<body>
<div id="map" class="map">
  <div th:if="${detailsData.serviceType==4}">
    <button class="data-btn" title="图层数据" onclick="showDatas(this)">
      <i aria-hidden="true" class="material-icons-outlined q-icon">table_chart</i>
    </button>
  </div>
  <div class="data-div" id="data" th:if="${detailsData.serviceType==4}" style="display: none">
    <div class="load-container load1" id="loadEffect"><div class="loader">Loading...</div></div>
    <div class="data-title" >
      <span th:text="${detailsData.name}" id="layerName"></span>
      <span>( 要素：<span id="dataSize"></span> )</span>
    </div>
    <div class="table-div">
      <table id="dataTable">
        <thead>
          <tr>
            <th th:each="attribute : ${baseData.attributes.attribute}"><span th:text="${attribute.name}"></span></th>
          </tr>
        </thead>
        <tbody>
        <!--<tr th:onclick="'javascript:showMapShape(this,\''+${infoStat.index}+'\');'" th:each="info,infoStat : ${shpInfo}" >-->
          <!--<td th:each="attribute : ${baseData.attributes.attribute}"><span th:text="${info[attribute.name]}"></span></td>-->
        <!--</tr>-->
        </tbody>

      </table>
    </div>
    <div class="table-footer tablePage">
      <select name="page_num">
        <option value="10" selected>10条/每页</option>
        <option value="20">20条/每页</option>
        <option value="30">30条/每页</option>
        <option value="40">40条/每页</option>
      </select>
    </div>
  </div>
</div>
<script type="text/javascript" th:inline="javascript">
  const layerIp = '../../../' //'http://192.168.9.12:8085/'
  var layerType = [[${detailsData.serviceType}]]
  let originProj4js = [[${proj4js}]] // 原始坐标系对应的参数
  var epsg = [[${detailsData.aliasName}]] // 1：代表地理坐标系，2：代表投影坐标系
  var epsgCode = [[${detailsData.epsg}]] // 坐标系编码
  let baseData = [[${baseData}]] // 原始坐标系数据
  var worldExtend = [[${detailsData.worldExtend}]]
  var projectedBounds = [[${detailsData.projectedBounds}]]
  var allFeatureLayer = [];
  var lastIndex;
  var columnsData;
  var tableDatas = []; //矢量图层数据
  var coordinate = [[${detailsData.serviceCoordinate}]]
  var layerName = [[${detailsData.name}]] // 服务名称
  const serviceUrl = [[${detailsData.serviceUrl}]] // 服务地址
  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=vec_w&tk=1d109683f4d84198e37a38c442d68311&x={x}&y={y}&l={z}'
          // url: 'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0'
        })
      })
    ],
    view: new ol.View({
      projection: 'EPSG:4326',
      center: [103.73,34.03],
      zoom: 5
    })
  });

  // 获取坐标系
  let center = baseData ? baseData.nativeBoundingBox : {}
  if(originProj4js.crs_type === '2' && originProj4js && center.maxx){
    let minCenter = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',[center.minx ? center.minx : 0, center.miny?center.miny:0]) // 源坐标系，目标坐标系，需要转换的值
    let maxCenter = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',[center.maxx ? center.maxx : 0, center.maxy?center.maxy:0]) // 源坐标系，目标坐标系，需要转换的值
    if(minCenter.toString() !== maxCenter.toString()){
      map.getView().fit([minCenter[0],minCenter[1],maxCenter[0],maxCenter[1]], map.getSize());
    }
  } else if(originProj4js.crs_type === '1' && center.maxx){
    map.getView().fit([center.minx,center.miny,center.maxx,center.maxy], map.getSize());
  }

  if(layerType === 1 || layerType === 4){
    let wmsLayer = new ol.layer.Image({
      source: new ol.source.ImageWMS({
        url: layerIp + serviceUrl, // 'http://192.168.9.12:8095/service/gis/wms/'+layerName,
        params: {
          uuid: createGuid(),
          srs: 'EPSG:4326'
        }
      })
    })
    map.addLayer(wmsLayer)
  }

  // var mapObj = document.getElementById('map')
  // mapObj.onclick = function(e){
  //   // alert('X ; '+ e.clientX  + 'Y: '+e.clientY);
  //   console.log(map.getEventCoordinate(e))
  //   var t = ol.proj.transform(map.getEventCoordinate(e), 'EPSG:3857', 'EPSG:4326');
  //   console.log(t);
  // }
  function showDatas(e){
    var dataObj = document.getElementById('data')
    if(tableDatas.length === 0){
      getTableDataList()
    }
    if(e.className.indexOf('active')>0){
      e.setAttribute('class','data-btn')
      dataObj.style.display = 'none'
    }else{
      e.setAttribute('class','data-btn active')
      dataObj.style.display = 'block'
    }
  }

  function getTableDataList () {
    let xhr = new XMLHttpRequest()
    xhr.onload = function (e) {
      if(this.status === 200||this.status === 304){
        let result = JSON.parse(this.response)
        tableDatas = result.data // 获取表格数据
        var baseData = [[${baseData}]]
        columnsData = (baseData && baseData.attributes) && baseData.attributes.attribute
        $('#loadEffect').remove()
        if(!tableDatas || tableDatas.length === 0){
          $('#dataTable tbody').html('<span class="no-data">没有可用数据</span>')
          return
        }
        $('#dataSize').html(tableDatas.length)
        loadTableData(1)
        reLoadPage()
        $('#loadEffect').remove()
      }
    }
    $('#loadEffect').show()
    xhr.open('post', '../../../service/gis/getLayerTable/?name='+layerName, true)
    xhr.send();
  }

  function showMapShape(e,index){
    allFeatureLayer.map(value =>{
      map.removeLayer(value)
    })
    allFeatureLayer = []
    lastIndex > -1 && $('#data'+lastIndex).removeClass('tr-active')
    if (lastIndex !== index) {
      $('#data'+index).addClass('tr-active')
    } else {
      lastIndex = ''
      return
    }

    var xhr = new XMLHttpRequest()
    xhr.onload = function (e) {
      if(this.status === 200||this.status === 304){
        let resData = this.response
        let datas = resData && resData.substring(resData.indexOf('('), resData.lastIndexOf(')')+1).replace(/\s+/g,",").replace(/\(/g,"[").replace(/\)/g,"]").replace(/,,/g,",")
        let type = resData.substring(0, resData.indexOf('(')-1)
        datas = JSON.parse(datas)
        if (type === 'POINT') {
          drawPoint(datas)
        } else {
          traverse(datas)
        }
      }
    }
    lastIndex = index
    xhr.open('get', '../../../service/gis/getLayerTable/'+index+'/?name='+layerName, true)
    xhr.send();

  }
  //选择每页显示多少条
  $('.table-footer').find('select[name="page_num"]').change(function () {
    $(".table-footer>span").remove();
    reLoadPage ()
  });

  /**
   * 循环遍历坐标数据
   * @param arr
   */
  function traverse(arr) {
    for (let a in arr) {
      if (arr[a] instanceof Array && arr[a][0] instanceof Array) {
        traverse(arr[a]); //递归遍历
      } else {
        drawShape(arr[a])
      }
    }
  }
  /**
   * 绘制图形
   * @param arr
   */
  function drawShape(dataArr){
    let lonLat = []
    for(let i = 0;i<dataArr.length-1;i+=2){
      var mid = [dataArr[i],dataArr[i+1]]
      if(originProj4js.crs_type === '2'){
        mid = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',mid) // 源坐标系，目标坐标系，需要转换的值
      }
      lonLat.push(mid)
    }
    var feature = new ol.Feature({
      geometry:new ol.geom.LineString(lonLat)
    });
    feature.setStyle(new ol.style.Style({
      stroke: new ol.style.Stroke({
        width: 3,
        color: [8, 243, 243, 1]
      })
    }))
    var source = new ol.source.Vector({
      features:[feature]
    });
    var featureLayer = new ol.layer.Vector({
      source: source
    })
    map.addLayer(featureLayer)
    allFeatureLayer.push(featureLayer)
  }

  /**
   * 绘制点
   * @param data
   */
  function drawPoint (data) {
    var lonLat = data
    // 投影坐标系统一转换成地理坐标系
    if(originProj4js.crs_type === '2'){
      lonLat = proj4(originProj4js.proj4js, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs', data) // 源坐标系，目标坐标系，需要转换的值
    }
    //点要素样式
    var pointStyle = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 5,
        fill: new ol.style.Fill({
          color: [8, 243, 243, 1]
        })
      })
    })
    var newFeature = new ol.Feature({
      geometry: new ol.geom.Point(lonLat)
    })
    var source = new ol.source.Vector({
      features: [newFeature]
    })
    var featureLayer = new ol.layer.Vector({
      source: source,
      style: pointStyle
    })
    map.addLayer(featureLayer)
    allFeatureLayer.push(featureLayer)
  }

  /**
   * 创建uuid
   * @returns {string}
   */
  function createGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0;
      var v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  /**
   * 加载table数据
   **/
  function loadTableData(page){
    let rows = $('.table-footer').find('select[name="page_num"] option:selected').val()
    let tBody = $('#dataTable tbody')
    tBody.html('')
    for(let i=(page-1)*rows; i< rows*page; i++){
      let val = tableDatas[i]
      if (!val) {
        break
      }
      let str = `<tr onclick="showMapShape(-1, `+i+`)" id="data`+i+`">`
      columnsData.map(col=>{
        str += `<td>${!val[col.name]?'':val[col.name]}</td>`
      })
      str += `</tr>`
      tBody.append(str);
    }
  }

  /**
   * 加载分页插件
   */
  function reLoadPage () {
    $('.table-footer').prepend("<span></span>");
    var currentRows = $('.table-footer').find('select[name="page_num"] option:selected').val()
    $('.table-footer').children("span").createPage({
      pageCount: Math.ceil(tableDatas.length/currentRows), //总页数
      current: 1,    //初始页数
      backFn: function (p) {    //p为当前页数，点击有效
        page = p
        loadTableData(p)
      }
    });
  }
</script>
</body>
</html>
